﻿using CommonDevelop;
using CommonDevelop.Cache;
using CommonDevelop.DB;
using CommonEngine;
using CommonFP;
using ManageDB;
using ManageDto;
using ManageRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ManageService
{
    /// <summary>
    /// 菜单模板资源服务层接口
    /// </summary>
    public interface IModuleService : IBaseService<Base_Module>
    {
        IEnumerable<ModuleDto> GetListByParentId(string ParentId);
        string GetParentName(string ParentId);
    }

    /// <summary>
    /// 菜单模板资源服务层
    /// </summary>
    public class ModuleService : BaseCacheService<Base_Module, IModuleRepository, ModuleDto>, IModuleService
    {
        /// <summary>
        /// 构造注入
        /// </summary>
        public ModuleService(IModuleRepository repository, IDCSCache MemoryCache)
            : base(repository, MemoryCache)
        {

        }

        protected override Expression<Func<ModuleDto, bool>> WhereDto(string keyword)
            => keyword.IsEmpty() ? (Expression<Func<ModuleDto, bool>>)null
            : t => t.ModuleCode.Contains(keyword) || t.FullName.Contains(keyword);

        public override string BuildSeq()
            => SugarBizDB.BuildSeq_01("Mod");

        public IEnumerable<ModuleDto> GetListByParentId(string ParentId)
        {
            var v = from p in this.GetEntity(ParentId)
                    from b in FP.Async(this.GetBind<Base_Module>(p))
                    select b.MapToList<Base_Module, ModuleDto>();

            return v.OrElse(() => FP.Async(Enumerable.Empty<ModuleDto>().ToList())).Result;
        }

        public string GetParentName(string ParentId)
            => this.Get<ModuleDto>(ParentId)
            .Match(() => string.Empty, a => a.FullName);
    }
}
